#!/bin/bash
#echo Export JVM Path
export XDCTOOLS_JAVA_HOME=~/ti/ccs910/ccs/eclipse/jre

#echo Export Lib Path
export LIB_PATH=$(dirname "$PWD")/cc2640r2f_oad_offchip_uart_stack/FlashROM

#echo Export App Path
export APP_PATH=$(dirname "$PWD")/cc2640r2f_oad_offchip_uart_app/FlashROM

#echo Export Hex Path
export HEX_PATH=$APP_PATH

#echo Export gmake Path
#export GMAKE_PATH=~/ti/ccs910/ccs/utils/bin/gmake
export GMAKE_PATH=make
thread_num=8

TPWD=$PWD

show_help(){
	echo -libbuild : Build the lib
	echo -libclean : Clean the lib make files
	echo -appbuild : Build the app
	echo -appclean : Clean the app make files
	echo -download : Download the hex file
	echo -appbuilddownload : Build the app and download the hex fils
}

lib_build(){
	#Entern the lib flash directory
	cd $LIB_PATH
	$GMAKE_PATH -k -j $thread_num all -O
	if [ $? -eq 0 ];then
		cd $TPWD
		echo Build Success.
		return 0
	else
		cd $TPWD
		echo Build Failed.
		return 1
	fi
}

lib_clean(){
	#Entern the lib flash directory
	cd $LIB_PATH
	$GMAKE_PATH -k -j $thread_num clean -O
	cd $TPWD
}

app_build(){
	#Entern the app flash directory
	cd $APP_PATH
	$GMAKE_PATH -k -j $thread_num all -O
	if [ $? -eq 0 ];then
		cd $TPWD
		echo Build Success.
		return 0
	else
		cd $TPWD
		echo Build Failed.
		return 1
	fi
}

app_clean(){
	#Entern the app flash directory
	cd $APP_PATH
	$GMAKE_PATH -k -j $thread_num clean -O
	cd $TPWD
}

download_hex(){
	#Entern the hex file path
	cd $HEX_PATH
	#Record the hex file name
	hexfile=`ls *.hex`

	cd $TPWD
	#Entern the uniflash tool directory
	cd uniflash_linux_64
	#Use uniflash tool to download the hex file
	. dslite_boarddownload.sh $HEX_PATH/$hexfile

	cd $TPWD

}

download_out(){
	#Entern the hex file path
	cd $HEX_PATH
	#Record the hex file name
	outfile=`ls *.out`

	cd $TPWD
	#Entern the uniflash tool directory
	cd uniflash_linux_64
	#Use uniflash tool to download the hex file
	. dslite_boarddownload.sh $HEX_PATH/$outfile

	cd $TPWD

}

run_param(){
	if [ "$1" == "-libbuild" ];then
		lib_build
	elif [ "$1" == "-libclean" ]; then
		lib_clean
	elif [ "$1" == "-appbuild" ]; then
		app_build
	elif [ "$1" == "-appclean" ]; then
		app_clean
	elif [ "$1" == "-download" ]; then
		download_hex
	elif [ "$1" == "-appbuilddownload" ]; then
		app_build
		if [ $? -eq 0 ]; then
			# download_hex
			download_out
		fi
	else
		echo error Paraments not mate:$1
	fi
}

if [ "$#" -eq 0 ]; then
	echo error No paraments.
	show_help
else
	run_param $1
fi
